package com.iseastar.guojiang;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.iseastar.BaseActivity2;
import com.iseastar.dianxiaosan.home.update.Update;
import com.iseastar.dianxiaosan.home.update.UpgradeBean;
import com.iseastar.guojiang.app.TimerService;
import com.iseastar.guojiang.dialog.DialogMgr;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.AppLogic;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.mine.SettingFragment;
import com.iseastar.guojiang.model.CourierTaskEventCommon;
import com.iseastar.guojiang.model.PassportTaskBackBean;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.ServiceTaskBean;
import com.iseastar.guojiang.newcabinet.DealTaskService;
import com.iseastar.guojiang.newcabinet.ServiceTaskFragment;
import com.iseastar.guojiang.passport.TaskPassportDialogActivity;
import com.iseastar.guojiang.print.BluetoothConnectionService;
import com.iseastar.guojiang.print.PrintFragment;
import com.iseastar.guojiang.util.MediaPlayerUtils;
import com.iseastar.guojiang.util.PollingUtils;
import com.iseastar.login.LoginChooseActivity;
import com.shouhuobao.station.R;
import com.tencent.android.tpush.XGPushClickedResult;
import com.tencent.android.tpush.XGPushManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import droid.frame.activity.ActivityMgr;
import droid.frame.utils.Android;
import droid.frame.utils.android.Log;
import droid.frame.utils.http.MsgID;
import droid.frame.view.ViewPagerExt;

/**
 * 果酱融合版-主页面
 *
 * @author coffee <br>
 * 2016-8-17下午2:58:15
 */
public class MainActivity extends BaseActivity2 implements OnClickListener, OnPageChangeListener {
    private ViewPagerExt mViewPager;
    // 上门-接驳、我的、更多
    private Fragment[] mFragments;
    private TextView[] mTabs = new TextView[3];

    public static AMapLocation aMapLocation = null;
    // 判断是否进入后台 (注意onPause、onStop都需要判断)
    private boolean isFromBackground = false;

    public static MainActivity instance;

    private boolean isWork = false;//是否开工 true 开工  false 收工
    private boolean isReceiverOrder = false;//是否接单 true 接单  false 不接单

    public void setWork(boolean work) {
        isWork = work;
    }

    public boolean isWork() {
        return isWork;
    }

    public boolean isReceiverOrder() {
        return isReceiverOrder;
    }

    public void setReceiverOrder(boolean receiverOrder) {
        isReceiverOrder = receiverOrder;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        instance = this;
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        // 检查版本升级
        AppHttp.getInstance().takeAppUpgrade(null);
        //崩溃日志上传
        AppHttp.getInstance().crashUpload();
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.main);
        super.findViewById();
        mViewPager = (ViewPagerExt) findViewById(R.id.viewpager);
        mViewPager.addOnPageChangeListener(this);
        // 订单列表--上门
        mFragments = new Fragment[3];
        mFragments[0] = new ServiceTaskFragment();
        mFragments[1] = new PrintFragment();
        mFragments[2] = new SettingFragment();
        mViewPager.setFragmentItems(getSupportFragmentManager(), mFragments);
        mViewPager.setOffscreenPageLimit(mTabs.length);

        mTabs[0] = (TextView) findViewById(R.id.main_tab_1);
        mTabs[1] = (TextView) findViewById(R.id.main_tab_2);
        mTabs[2] = (TextView) findViewById(R.id.main_tab_3);
        mTabs[0].setOnClickListener(this);
        mTabs[1].setOnClickListener(this);
        mTabs[2].setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_tab_1:
                mViewPager.setCurrentItem(0);
                setTabBackground(v);
                break;
            case R.id.main_tab_2:
                mViewPager.setCurrentItem(1);
                setTabBackground(v);
                break;
            case R.id.main_tab_3:
                mViewPager.setCurrentItem(2);
                setTabBackground(v);
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageSelected(int position) {
        if (mFragments != null) {
            setTabBackground(mTabs[position]);
//            mFragments[position].onResume();
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {

    }

    private void setTabBackground(View v) {
        if (mTabs[0].getId() == v.getId()) {
            mTabs[0].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_lanshou_selected, 0, 0);
            mTabs[1].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_print_normal, 0, 0);
            mTabs[2].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_person_normal, 0, 0);
            mTabs[0].setTextColor(getResources().getColor(R.color.app_theme_color1));
            mTabs[1].setTextColor(getResources().getColor(R.color.app_font_1));
            mTabs[2].setTextColor(getResources().getColor(R.color.app_font_1));

        } else if (mTabs[1].getId() == v.getId()) {
            mTabs[0].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_lanshou_normal, 0, 0);
            mTabs[1].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_print_selected, 0, 0);
            mTabs[2].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_person_normal, 0, 0);
            mTabs[0].setTextColor(getResources().getColor(R.color.app_font_1));
            mTabs[1].setTextColor(getResources().getColor(R.color.app_theme_color1));
            mTabs[2].setTextColor(getResources().getColor(R.color.app_font_1));

        } else if (mTabs[2].getId() == v.getId()) {
            mTabs[0].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_lanshou_normal, 0, 0);
            mTabs[1].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_print_normal, 0, 0);
            mTabs[2].setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.bottom_menu_person_selected, 0, 0);
            mTabs[0].setTextColor(getResources().getColor(R.color.app_font_1));
            mTabs[1].setTextColor(getResources().getColor(R.color.app_font_1));
            mTabs[2].setTextColor(getResources().getColor(R.color.app_theme_color1));
        }
    }

    /**
     *
     */
    //设置点击返回键
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dealTaskData(CourierTaskEventCommon courierTaskEventCommon) {
        if (!AppLogic.isEmptyForList()) {
            ServiceTaskBean bean = AppLogic.getPassportList().get(0);
            Intent intent = new Intent(getApplication(), TaskPassportDialogActivity.class);
            intent.putExtra("item", bean);
            ActivityMgr.peek().startActivity(intent);
        }
        if (courierTaskEventCommon != null && courierTaskEventCommon.getBackBean() != null) {
            PassportTaskBackBean backBean = courierTaskEventCommon.getBackBean();
            ServiceTaskBean newTaskBean = backBean.getTaskBean();
            ArrayList<ServiceTaskBean> cancelList = backBean.getCancelList();
            if (newTaskBean != null || (cancelList != null && cancelList.size() > 0)) {
                ((ServiceTaskFragment) mFragments[0]).refreshTaskData();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        instance = this;
        /**
         * 从后台进入的
         */
        if (isFromBackground) {
            // 获取app配置
            ((ServiceTaskFragment) mFragments[0]).refreshTaskData();
            Log.d("33333", "mainactivity onresume:" + isFromBackground);
            PollingUtils.stopPollingService(this, TimerService.class, TimerService.ACTION);
            isFromBackground = false;
        }
        //检查是否登录
        boolean isLogin = AppLogic.checkLogin(getContext());
        if (isLogin == false) {
            startActivity(new Intent(getContext(), LoginChooseActivity.class));
            finish();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 判断是否进入后台
        //        isFromBackground = updateState(getContext());
        isFromBackground = !Android.isAppOnForeground(getContext());
        XGPushClickedResult clickedResult = XGPushManager.onActivityStarted(this);
        if (clickedResult != null) {
            String customContent = clickedResult.getCustomContent();
            Log.d("44444", customContent);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 判断是否进入后台
        //        isFromBackground = updateState(getContext());
        isFromBackground = !Android.isAppOnForeground(getContext());
        if (isFromBackground) {
            //开工和收工状态有问题,先不进行处理
            Log.d("11111", "首页定位开工：" + isWork + ",接单状态：" + isReceiverOrder);
            //如果开工并且在接收任务时
            if (isWork && isReceiverOrder) {
                startOrStopRefreshLocation(true);
                alarmCpuWake();
                MediaPlayerUtils.getInstance().playerMusic("courier_silence.mp3", true);
            } else {
                startOrStopRefreshLocation(false);
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("33333", "mainactivity.ondestroy()");
        EventBus.getDefault().unregister(this);
        PollingUtils.stopPollingService(this, TimerService.class, TimerService.ACTION);
        Intent intent = new Intent(getContext(), BluetoothConnectionService.class);
        intent.setPackage(getPackageName());
        stopService(intent);
        aMapLocation = null;
        instance = null;
        AppLogic.getPassportList().clear();
        AppLogic.getAppBackgroundPassportList().clear();
    }

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            case MsgID.net_unavailable:
                showToast(msg.obj.toString());
                return false;
            // 版本更新
            case com.iseastar.guojiang.consts.MsgID.station_update:
                final ReqResult<UpgradeBean> result = JSON.parser(msg.obj, UpgradeBean.class);
                if (checkLoginStatus(result)) {
                    getContext().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            UpgradeBean item = result.getResult();
                            if (item == null || item.getIsNeedUpdate() == 0) {
                                if (msg.arg1 > 0) {
                                    DialogMgr.showNoUpdate(getContext());
                                }
                            } else if (item.getIsNeedUpdate() == 1 || item.getIsNeedUpdate() == 2) {
                                Update update = new Update(getContext());
                                update.doNewVersionUpdate(item.getDownloadUrl(), item.getDescription(), item.getIsNeedUpdate());
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        instance = this;
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            boolean taskException = bundle.getBoolean("taskexception");
            if (taskException) {
                refreshHomeData();
            }
        }
        isFromBackground = false;//
    }

    public void refreshHomeData() {
        ((ServiceTaskFragment) mFragments[0]).refreshTaskData();
    }

    /**
     * 设置火箭侠接单任务状态
     */
    public void setCouirerReceiveOrderStatus() {
        ((ServiceTaskFragment) mFragments[0]).updateCourierStatus();
    }

    //点击返回键返回桌面而不是退出程序
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 在应用退到后台后，使用alarmManager启动一个timer来进行唤醒cpu
     */
    private void alarmCpuWake() {
        PollingUtils.startPollingService(getContext(), 10, TimerService.class, TimerService.ACTION);
    }

    /**
     * 启动或关闭上传位置的service {@link com.iseastar.guojiang.newcabinet.DealTaskService}
     *
     * @param isStart true 启动  false  关闭
     */
    public void startOrStopRefreshLocation(boolean isStart) {
        if (!ActivityMgr.isServiceRunning(BeeApplication.getContext(), "com.iseastar.guojiang.newcabinet.DealTaskService") && isStart) {
            Intent intent = new Intent();
            intent.setClass(BeeApplication.getContext(), DealTaskService.class);
            intent.putExtra("isStop", !isStart);
            BeeApplication.getContext().startService(intent);
        } else if (isStart) {
            DealTaskService.startWorkLocation(false);
        } else {
            if (!isStart) {
                PollingUtils.stopPollingService(getContext(), TimerService.class, TimerService.ACTION);
                DealTaskService.startWorkLocation(true);
                Intent intent = new Intent();
                intent.setClass(BeeApplication.getContext(), DealTaskService.class);
                intent.putExtra("isStop", isStart);
                BeeApplication.getContext().stopService(intent);
            }
        }
    }
}
